<!--
  * 采购订单表
  *
  * @Author:    zzw
  * @Date:      2024-10-08 17:37:12
  * @Copyright  jz
-->
<template>
    <div>
        <a-modal :title="form.id ? '编辑' : '添加'" width="60%" :open="visibleFlag" @cancel="onClose" :maskClosable="false"
            :destroyOnClose="true">
            <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 7 }">

                <a-row>
                    <a-col :span="12">
                        <a-form-item label="采购订单" name="orderCode">
                            <a-input-search v-model:value="form.orderCode" placeholder="采购订单" @search="onSearch" />
                            <!-- <a-input :disabled="disabled" style="width: 100%" v-model:value="form.orderCode"
                            placeholder="采购订单编号" /> -->
                        </a-form-item>
                    </a-col>
                    <!-- <a-col :span="12">
                        <a-form-item label="入库时间" name="orderTime">
                            <a-date-picker  v-model:value="form.orderTime"
                                :presets="defaultTimeRanges" style="width: 100%" @change="onChangeOrderTime" />
                        </a-form-item>
                    </a-col> -->
                    <a-col :span="12">
                        <a-form-item label="备注" name="remark">
                            <a-input :disabled="disabled" style="width: 100%" v-model:value="form.remark"
                                placeholder="备注" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="附件" name="fileUrl">
                            <a-button type="primary" @click="showUploadModal" size="small">
                                <template #icon><cloud-upload-outlined /></template>上传文件
                            </a-button>
                            <a-button :disabled="disabled" type="link" v-if="fileName" @click="viewFile">附件</a-button>
                        </a-form-item>
                        <a-modal v-model:open="uploadModalFlag" title="上传文件" @onCancel="hideUploadModal"
                            @ok="hideUploadModal">
                            <FileUpload :disabled="disabled" list-type="text" :maxUploadSize="5" buttonText="点击上传文件"
                                :defaultFileList="[]" :multiple="true"
                                :folder="FILE_FOLDER_TYPE_ENUM.PURCHASE_ORDER_ATTACHMENT" @change="fileChange" />
                        </a-modal>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="审批人" name="approverId">
                            <a-select style="width: 85%" v-model:value="form.approverId" placeholder="审批人"
                                :allowClear="true">
                                <a-select-option v-for="item in dictValueList" :key="item" :value="item.employeeId">
                                    {{ item.actualName }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <!-- <a-col :span="12">
                        <a-form-item label="入库状态" name="inboundStatus">
                            <a-select :disabled="disabled" v-model:value="form.inboundStatus" style="width: 100%"
                                :options="[{ value: 0, label: '待入库' }, { value: 1, label: '已入库' }]"></a-select>
                        </a-form-item>
                    </a-col> -->

                    <!-- table start -->
                    <a-col :span="24" style="padding:0 0 20px 20px;">
                        <a-tabs activeKey="1">
                            <a-tab-pane key="1" tab="入库产品清单">
                                <a-table size="small" :dataSource="purchaseOrderGoodsListVOList" :columns="columns"
                                    rowKey="id" bordered :pagination="false"
                                    :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange2 }">
                                    <template #bodyCell="{ text, record, column, index }">
                                        <template v-if="column.dataIndex === 'index'">
                                            {{ index + 1 }}
                                        </template>
                                        <template v-if="column.dataIndex === 'thisInboundQuantity'">
                                            <a-input-number :min="0" v-model:value="record.thisInboundQuantity"
                                                :disabled="record.disabled"></a-input-number>
                                        </template>

                                    </template>
                                </a-table>

                            </a-tab-pane>
                        </a-tabs>


                    </a-col>
                    <!-- table end -->
                </a-row>
            </a-form>

            <template #footer>
                <a-space v-if="form.type != 3">
                    <a-button @click="onClose">取消</a-button>
                    <a-button type="primary" @click="onSubmit">保存</a-button>
                </a-space>
            </template>
        </a-modal>
        <a-modal v-model:open="draweropen" class="custom-class" root-class-name="root-class-name"
            :root-style="{ color: 'blue' }" style="color: red;width: 60%;" title="采购订单">
            <a-table size="small" :dataSource="tableData2" :columns="columns2" rowKey="id" bordered :pagination="false"
                :scroll="{ x: 1100 }"
                :rowSelection="{ selectedRowKeys: selectedRowKeysArray, onChange: onSelectChange, type: 'radio' }">
                <template #bodyCell="{ text, record, column }">
                    <!-- orderStatus -->
                    <template v-if="column.dataIndex === 'orderStatus'">
                        {{ ['待审批', '审批未通过', '', '审批通过', '已收货入库'][record.orderStatus] }}
                    </template>

                </template>
            </a-table>
            <!---------- 表格 end ----------->

            <div class="smart-query-table-page">
                <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS"
                    :defaultPageSize="queryForm.pageSize" v-model:current="queryForm.pageNum"
                    v-model:pageSize="queryForm.pageSize" :total="total" @change="queryData" @showSizeChange="queryData"
                    :show-total="(total) => `共${total}条`" />
            </div>
        </a-modal>
    </div>

</template>
<script setup>
import { reactive, ref, nextTick, onMounted } from 'vue';
import _ from 'lodash';
import { message } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { purchaseInboundApi } from '/@/api/business/purchaseInventory/index';

import { purchaseOrderApi } from '/@/api/business/purchase/index';
import { smartSentry } from '/@/lib/smart-sentry';

import { dictApi } from '/src/api/support/dict-api';
const disabled = ref(false);

const draweropen = ref(false)

const purchaseOrderGoodsListVOList = ref([])

function onSelectChange(selectedRowKeys, selectedRows) {
    purchaseOrderGoodsListVOList.value = selectedRows[0].purchaseOrderGoodsListVOList
    form.orderCode = selectedRows[0].orderCode
    draweropen.value = false
}

function onSelectChange2(selectedRowKeys, selectedRows) {

    form.inboundGoodsListUpdateForms = selectedRows

}
const dictValueList = ref([])
async function queryDict() {
    let res = await dictApi.ProjecPersonid();
    dictValueList.value = res.data;
}
const columns2 = ref([
    {
        title: '订单编码',
        dataIndex: 'orderCode',
        width: 130,
        ellipsis: true,
    },
    {
        title: '项目',
        dataIndex: 'projectName',
        width: 150,
        ellipsis: true,
    },

    {
        title: '生成时间',
        dataIndex: 'orderTime',
        width: 150,
        ellipsis: true,
    },

    {
        title: '附件',
        dataIndex: 'fileUrl',
        width: 150,
        ellipsis: true,
    },
    {
        title: '状态',
        dataIndex: 'orderStatus',
        width: 120,
        ellipsis: true,
    },
    {
        title: '优惠率',
        dataIndex: 'discountRatio',
        width: 120,
        ellipsis: true,
    },
    {
        title: '结算账户',
        dataIndex: 'settlementAccount',
        width: 120,
        ellipsis: true,
    },
    {
        title: '已支付订金金额',
        dataIndex: 'depositPaid',
        width: 120,
        ellipsis: true,
    },

    {
        title: '审批人姓名',
        dataIndex: 'approverName',
        width: 120,
        ellipsis: true,
    },
    {
        title: '审批时间',
        dataIndex: 'approvalTime',
        width: 120,
        ellipsis: true,
    },
    {
        title: '审批意见',
        dataIndex: 'approvalRemark',
        width: 120,
        ellipsis: true,
    },
    {
        title: '备注',
        dataIndex: 'remark',
        width: 120,
        ellipsis: true,
    },

]);
// ------------------------ 事件 ------------------------
const emits = defineEmits(['reloadList']);


const tableData = ref([])
const columns = ref([
    {
        title: '序号',
        dataIndex: 'index',
        width: 50,
        align: 'center'
    },
    {
        title: '编码',
        dataIndex: 'code',
        ellipsis: true,
    },
    {
        title: '名称',
        dataIndex: 'goodsName',
        ellipsis: true,
    },
    {
        title: '产品数量',
        dataIndex: 'quantity',

    },
    {
        title: '已入库数量',
        dataIndex: 'inboundQuantity',
        ellipsis: true,
    },
    {
        title: '本次入库数量',
        dataIndex: 'thisInboundQuantity',
        width: 150,
    },

    {
        title: '产品税率',
        dataIndex: 'taxRate',
        ellipsis: true,
    },
    {
        title: '供应商',
        dataIndex: 'supplierName',
        ellipsis: true,
    },

]);

// ------------------------ 显示与隐藏 ------------------------
// 是否显示
const visibleFlag = ref(false);

function show(rowData) {
    purchaseOrderGoodsListVOList.value = []
    queryDict()
    purchaseOrderGoodsListVOList.value = rowData.purchaseInboundGoodsListVOS

    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
        Object.assign(form, rowData);
    }
    if (rowData.purchaseOrderGoodsListVOList && rowData.purchaseOrderGoodsListVOList.length) {
        tableData.value = rowData.purchaseOrderGoodsListVOList.map(i => {
            return { ...i }
        })
        tableData.value.forEach(item => item.taxRate = item.taxRate * 100)
    }
    if (form.discountRatio) {
        form.discountRatio = form.discountRatio * 100
    }




    visibleFlag.value = true;
    nextTick(() => {
        formRef.value.clearValidate();
    });
}

function onClose() {
    tableData.value = []
    Object.assign(form, formDefault);
    visibleFlag.value = false;
}

// ------------------------ 表单 ------------------------

// 组件ref
const formRef = ref();

const formDefault = {
    id: undefined,
    orderCode: undefined, //采购订单编号
    inboundTime: undefined, //入库时间
    remark: undefined, //备注
    fileUrl: undefined, //附件
    inboundStatus: undefined, //入库状态
    otherExpenses: undefined, //其他费用
    inboundGoodsListUpdateForms: [],
    approverId: undefined,
    approverName: undefined
};

let form = reactive({ ...formDefault });

const rules = {
    orderCode: [{ required: true, message: '采购订单编号 必填' }],
    inboundTime: [{ required: true, message: '入库时间 必填' }],
};

// 点击确定，验证表单
async function onSubmit() {
    let obj = dictValueList.value.filter((e) => {
        return e.employeeId == form.approverId
    })
    form.approverName = obj[0].actualName
    try {
        await formRef.value.validateFields();
        save();
    } catch (err) {
        message.error('参数验证错误，请仔细填写表单数据!');
    }
}

// 新建、编辑API
async function save() {
    SmartLoading.show();
    try {
        console.log(tableData.value)
        if (tableData.value && tableData.value.length) {
            if (form.id) {
                form.orderGoodsListUpdateForms = tableData.value.map(item => {
                    item.taxRate = item.taxRate / 100;
                    return item;
                })
            } else {
                form.orderGoodsListAddForms = tableData.value.map(item => {
                    item.taxRate = item.taxRate / 100;
                    return item;
                })
            }


        }

        let obj = { ...form }
        if (obj.discountRatio) {
            obj.discountRatio = obj.discountRatio / 100
        }
        if (form.id) {
            await purchaseInboundApi.update(obj);
        } else {
            await purchaseInboundApi.add(obj);
        }
        message.success('操作成功');

        emits('reloadList');
        onClose();
    } catch (err) {
        smartSentry.captureError(err);
    } finally {
        SmartLoading.hide();
    }
}
// 获取项目下拉
const projectOptions = ref([])
function getProject() {
    purchaseOrderApi.project().then(res => {
        projectOptions.value = res.data.map(element => {
            return {
                label: element.customerName,
                value: element.id
            }
        })
    })
}
// 获取供应商下拉
const subcontractorInfoOptions = ref([])
function getSubcontractorInfo() {
    purchaseOrderApi.subcontractorInfo().then(res => {
        subcontractorInfoOptions.value = res.data.map(element => {
            return {
                label: element.companyName,
                value: element.id
            }
        })
    })
}
const goodsOptions = ref([])
function getGoods() {
    purchaseOrderApi.goods().then(res => {
        goodsOptions.value = res.data.map(element => {
            return {
                label: element.goodsName,
                value: element.goodsId
            }
        })
    })
}

const orderOptions = ref([])

function add() {
    tableData.value.push({
        goodsId: '',
        quantity: '',
        taxRate: ''
    })
}

function onSearch() {
    queryData()
    draweropen.value = true
}

const queryFormState = {
    // projectId: undefined, //订单归属项目ID
    // orderStatus: undefined, //订单状态（0待审批、1审批未通过、2待支付、3已支付、4已收货入库）
    // operatorId: undefined, //操作人ID
    // orderTime: [], //订单生成时间
    // orderTimeBegin: undefined, //订单生成时间 开始
    // orderTimeEnd: undefined, //订单生成时间 结束
    // orderCode: undefined, //订单编码
    // supplierId: undefined, //供应商ID
    pageNum: 1,
    pageSize: 10,
};
// 查询表单form
const queryForm = reactive({ ...queryFormState });
// 表格数据
const tableData2 = ref([]);
// 总数
const total = ref(0);
async function queryData() {

    try {
        let queryResult = await purchaseOrderApi.queryPage(queryForm);
        tableData2.value = queryResult.data.list;
        total.value = queryResult.data.total;
    } catch (e) {
        smartSentry.captureError(e);
    } finally {
        // tableLoading.value = false;
    }
}
function onDelete(index) {
    tableData.value.splice(index, 1)
}
onMounted(() => {

    // getProject();
    // getSubcontractorInfo();
    // getGoods();
})
defineExpose({
    show,
});
</script>